import "./login.scss";

import { Form, Input, Button, message } from "antd";
import { login } from '@/api/login'
import { useHistory } from "react-router-dom"
import { useDispatch } from 'react-redux'
import { userSetToken } from '@/store/usersSlice'



const Login = () => {

  const dispatch = useDispatch()
  let history = useHistory()

  const handlerLogin = ( {username, password} ) => {
    login({ username, password })
    .then(res => {
      
        let { token } = res.data
        
        dispatch(userSetToken({ token: token }))

        history.push('/')

    }).catch(res => {
        console.log('catch', res)
        message.error({content: '服务器错误，请联系管理员'})
    })
  }

  const onFinish = (values) => {
    console.log("sucess", values);
    handlerLogin(values)
  };

  const onFinishFailed = (errorInfo) => {
    console.log("failed", errorInfo);
  };
  

  return (
    <div className="login-container">
      <div className="login-block">
        <div className="login-text">Login</div>
        <Form
          name="basic"
          initialValues={{ remember: true }}
          onFinish={onFinish}
          onFinishFailed={onFinishFailed}
          autoComplete="off"
        >
          <Form.Item
            name="username"
            rules={[{ required: true, message: "请输入账号" }]}
          >
            <Input  placeholder="账号"/>
          </Form.Item>

          <Form.Item
            name="password"
            rules={[{ required: true, message: "请输入密码" }]}
          >
            <Input.Password  placeholder="密码"/>
          </Form.Item>
          <Form.Item>
            <Button className="button-width" type="primary" htmlType="submit">
              登录
            </Button>
          </Form.Item>
        </Form>
      </div>
    </div>
  );
};

export default Login;
